'''
Created on 28/05/2010

@author: eh01
'''
from optparse import OptionParser
from string import Template
import os
import sys
    
def generate_serialised_edais_artefacts(edais_directory):
    """
    Traverses the edais directory looking for WSDL and Schema files to process. Extracts the contents of these
    files and plugs them into a resource template file with the appropriate metadata. This script has to be executed
    in edais directory as it has hardcoded relative paths to the artefacts folder. We used a template here that is
    a serialised empty resource and substitute pre defined parameters to populate the xml. We do this instead of using
    the serialise function on Resource as it does not handle writing out data wrapped in CDATA well. The script adds
    auto load functionality to each resource so it is loaded into Spaces at startup.
    
    :param edais_directory: Root directory of eDAIS artefacts.
    :rtype: None
    """       
    wsdls_names_processed = []
    schemas_name_processed = []
    
    # open up the template file
    artefact_template_fo = open('artefacts/artefact_template.xml', 'r')
    artefact_template_string = artefact_template_fo.read()
    
    # walk through the directory tree
    for cur_dir, dirs, files in os.walk(edais_directory):
        # relative path is the path of the edais artefact relative to the 
        # root of the edais directory
        relative_path = cur_dir.replace(edais_directory, '').replace('\\', '/')
        if relative_path.startswith('/'):
            relative_path = relative_path[1:]
        for file in files:
            # handle wsdls
            if file.endswith('.wsdl'):
                wsdl_file_object = open((os.path.join(cur_dir, file)),'r')
                # populate the params. The params here should match those in the template file
                params = {'artefact_type':"term:eplanning/edais/wsdl",
                          'artefact_file_name':file,
                          'artefact_content':wsdl_file_object.read(),
                          'edais_artefact_path':"/".join([relative_path,file])
                          }
                template = Template(artefact_template_string)
                serialised_resource = template.substitute(params)
                # write out the serialised resource to the wsdl directory
                new_artefact_file = open("artefacts/wsdl/%s" % file.replace('.wsdl','.xml'), "w")
                new_artefact_file.write(serialised_resource)
                new_artefact_file.close()
                print "Processed %s" % file
                wsdls_names_processed.append(file)
                # check for duplicates. Since we are not preserving the folder structure,
                # we need to make sure that no two wsdl files are named the same
                if len(wsdls_names_processed) != len(set(wsdls_names_processed)):
                    raise Exception('Two wsdl files named %s' % file)
            # handle schemas
            elif file.endswith('.xsd'):
                schema_file_object = open((os.path.join(cur_dir, file)),'r')
                # populate the params. The params here should match those in the template file
                params = {'artefact_type':"term:eplanning/edais/schema",
                          'artefact_file_name':file,
                          'artefact_content':schema_file_object.read(),
                          'edais_artefact_path':"/".join([relative_path,file])
                          }
                template = Template(artefact_template_string)
                serialised_resource = template.substitute(params)
                # write out the serialised resource to the schema directory                
                new_artefact_file = open("artefacts/schema/%s" % file.replace('.xsd','.xml'), "w")
                new_artefact_file.write(serialised_resource)
                new_artefact_file.close()
                print "Processed %s" % file
                schemas_name_processed.append(file)
                # check for duplicates. Since we are not preserving the folder structure,
                # we need to make sure that no two schema files are named the same
                if len(schemas_name_processed) != len(set(schemas_name_processed)):
                    raise Exception('Two schema files named %s' % file)                            
    artefact_template_fo.close()
    
    print "wsdls processed: %d" % len(wsdls_names_processed)
    print "schemas processed: %d" % len(schemas_name_processed)
    
if __name__ == '__main__':
    usage = "%s options. "
    parser = OptionParser(usage=usage % sys.argv[0])

    parser.add_option("--d", 
                      dest="edais_directory",
                      action="store", type="string",
                      default=None,
                      help="Root directory of eDAIS artefacts.")

    (options, args) = parser.parse_args()
    generate_serialised_edais_artefacts(options.edais_directory)